<?php
if (!defined('sugarEntry')) {
    session_start();
    session_destroy();
    header("Location: ../iphone.php");
}
/*********************************************************************************
* SugarCRM is a customer relationship management program developed by
* SugarCRM, Inc. Copyright (C) 2004 - 2007 SugarCRM Inc.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License version 3 as published by the
* Free Software Foundation with the addition of the following permission added
* to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
* IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
* OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, see http://www.gnu.org/licenses or write to the Free
* Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA.
*
* You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
* SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU General Public License version 3.
*
* In accordance with Section 7(b) of the GNU General Public License version 3,
* these Appropriate Legal Notices must retain the display of the "Powered by
* SugarCRM" logo. If the display of the logo is not reasonably feasible for
* technical reasons, the Appropriate Legal Notices must display the words
* "Powered by SugarCRM".
********************************************************************************/
/*********************************************************************************
* Function:    sugar-iphone-client for SugarCRM
* Description: Functions used in detail view
* Author:      Editha Kuske - 2008, Richard John Jensen 2009
* Revision:      $Id: detail_masks.php 6 2009-12-26 16:59:05Z richardjohnjensen $
********************************************************************************/

function time2db($str_date_time) {
    $sec = strtotime($str_date_time) - ($_SESSION['gmt_server_offset']*3600);
    return date("Y-m-d H:i:s", $sec);
}
function db2time($str_date_time) {
    $sec = strtotime($str_date_time) + ($_SESSION['gmt_server_offset']*3600);
    return date("Y-m-d H:i:s", $sec);
}

function replaceByValues($statement) {
    global $ar_meta_fields;
    
    $har = split("\?", $statement);
    for ($i; $i<count($har); $i++) {
        $hc = substr($har[$i], 0, 1);
        if ($hc == '+') {
            $hname = substr($har[$i], 1);
            $har[$i] = $ar_meta_fields[$hname]['value'];
        }
    }
    $statement = implode("", $har);
    
    return $statement;
    
}

function getFloat($number) {
    $text = trim((string)$number);
    $text = ltrim($text, "0");
    $hstr = "";
    
    for ($i=0; $i < strlen($text); $i++) {
        switch ($text[$i]) {
			case ', ':
				$hstr.= '.';
				break;
			case '.':
			case '0':
			case '1':
			case '2':
			case '3':
			case '4':
			case '5':
			case '6':
			case '7':
			case '8':
			case '9':
				$hstr.= $text[$i];
				break;
			default:
				return -1;
        }
    }
    return(float) $hstr;
}
function getInt($number) {
    $text = trim((string)$number);
    $text = ltrim($text, "0");
    
    if (strlen($text) == 0) {
        return 0;
    }
    
    $hstr = "";
    
    for ($i=0; $i < strlen($text); $i++) {
        switch ($text[$i]) {
			case '0':
			case '1':
			case '2':
			case '3':
			case '4':
			case '5':
			case '6':
			case '7':
			case '8':
			case '9':
				$hstr.= $text[$i];
				break;
			default:
				return -1;
        }
    }
    return(int) $hstr;
}

function getCurrency($value) {
    $fval = getFloat($value);
    
    if ($fval == -1) {
        return -1;
    }
    
    return round($fval, 2);
}

function getDatum($value) {
    if (empty($value)) {
        return -1;
    }
    
    $value = str_replace(".", "-", $value);
    $har = split('-', $value);
    
    if (count($har) < 3) {
        return "";
    }
    
    if(strlen($har[2]) == 4) {// Jahr steht hinten Bsp: 1.2.2009
        $value = $har[2]."-".$har[1]."-".$har[0];
    } else if(strlen($har[0]) != 4) {// sonst muss es vorne stehen
        return "";
    }
    
    $d1 = strtotime($value);
    $d2 = date('Y-m-d', $d1);
    if ($d2 == '1970-01-01') {
        return "";
    }
    
    return $d2;
}

function getPercent($value) {
    $fval = getFloat($value);
    
    if ($fval == -1) {
        return -1;
    }
    
    if ($fval > 100) {
        return -1;
    }
    
    //   return round($fval, 0);
    return round($fval, 0);
}
function getHours($value) {
    $int_hours = getInt($value);
    
    if ($int_hours == -1) {
        return -1;
    }
    
    if ($int_hours > 100) {
        return -1;
    }
    
    return $int_hours;
}

function getDuration($value, &$int_hours, &$int_minutes) {
    $str_value = trim($value);
    $hpos = strpos($str_value, ':');
    if ($hpos === false) {
        return -1;
    }
    
    $hours = substr($str_value, 0, $hpos);
    $minutes = substr($str_value, $hpos+1);
    
    $int_hours = getInt($hours);
    if ($int_hours == -1) {
        return -1;
    }
    
    $int_minutes = getInt($minutes);
    if ($int_minutes == -1) {
        return -1;
    }
    
    if (($int_hours >= 100)||($int_minutes >= 60)) {
        return -1;
    }
    
    if ($int_minutes > 0) {
        if ($int_minutes < 15) {
            $int_minutes = 15;
        } else if ($int_minutes < 30) {
            $int_minutes = 30;
        } else {
            $int_minutes = 45;
        }
    }
    return 1;
}

function getTime($value) {
    $str_value = trim($value);
    $hpos = strpos($str_value, ':');
    if ($hpos === false) {
        return "";
    }
    
    $hours = substr($str_value, 0, $hpos);
    $minutes = substr($str_value, $hpos+1);
    
    $int_hours = getInt($hours);
    if ($int_hours == -1) {
        return "";
    }
    
    $int_minutes = getInt($minutes);
    if ($int_minutes == -1) {
        return "";
    }
    
    if (($int_hours >= 24) || ($int_minutes > 59)) {
        return "";
    }
    
    if ($int_hours < 10) {
        $str_hours = "0".$int_hours;
    } else {
        $str_hours = (string)$int_hours;
    }
    
    $str_minutes = (string)$int_minutes;
    if (strlen($str_minutes) < 2) {
        $str_minutes = $str_minutes."0";
    }
    return $str_hours.":".$str_minutes;
}

// ----------------------------------------------------------------
function check_field(&$field) {
    
    $value = $field['value'];
    $field['err_str'] = "";
    
    // ---- required - empty -------
    if (empty($value)) {
        if ($field['required']) {
            switch ($field['fieldtype']) {
				case "enum":
					break;
					
				default:
					$field['err_str'] = "Required field '".$field['fieldname']."' mustn't be empty!";
					return 0;
            }
        }
    }
    
    switch ($field['fieldtype']) {
		case 'currency':
			$validated_value = getCurrency($value);
			if ($validated_value == -1) {
				$field['err_str'] = "Currency not valid";
			}
			break;		
		case 'date':
		case 'date_part':
			$validated_value = getDatum($value);
			if ($validated_value == "") {
				$field['err_str'] = "Date (YYYY-mm-dd) not valid";
			}
			break;			
		case 'time':
		case 'time_part':
			$validated_value = getTime($value);
			
			if ($validated_value == "") {
				$field['err_str'] = "Time (hh:mm) not valid";
			} else {
				$validated_value.= ":00";
			}
			break;		
		case 'percent':
			$validated_value = getPercent($value);
			if ($validated_value == -1) {
				$field['err_str'] = "Percent not valid";
			}
			break;		
		case 'hours':
			$validated_value = getHours($value);
			if ($validated_value == -1) {
				$field['err_str'] = "Hours not valid";
			}
			break;	
		default:
			$validated_value = $value;
			break;
    }
    
    if ($field['err_str'] != "") {
        return 0;
    }
    
    $field['value'] = $validated_value;
    return 1;
}

// ----------------------------------------------------------------
function check_posted_fields() {
    global $ar_meta_fields;
    
    $is_ok = 1;
    foreach($ar_meta_fields AS $key => $val) {
        if (isset($_POST[$key])) {
            $ar_meta_fields[$key]['value'] = $_POST[$key];
            if (!check_field($ar_meta_fields[$key])) {
                $is_ok = 0;
            }
        }
    }
    if (isset($_POST['duration_hours']) && ($ar_meta_fields['duration']['required'])) {
        if (empty($ar_meta_fields['duration_hours']['value']) && ($ar_meta_fields['duration_minutes']['value'] == "00")) {
            $ar_meta_fields['duration']['err_str'] = "Required field mustn't be empty!";
            $is_ok = 0;
        }
        if (!empty($ar_meta_fields['duration_hours']['err_str'])) {
            $ar_meta_fields['duration']['err_str'] = $ar_meta_fields['duration_hours']['err_str'];
            $is_ok = 0;
            //print_r($ar_meta_fields);
        }
    }
    //if (!$is_ok)  print_r($ar_meta_fields);
    return $is_ok;
}

// ----------------------------------------------------------------
function execute_submit(&$bean_id, $ar_bean_descr) {
    global $_POST, $ar_meta_fields, $sugar_soap_client;
    
    $module_name = $ar_bean_descr['module_name'];
    $thin_bean = $ar_bean_descr['thin_bean'];
    
    $id = 0;
    
    if (!check_posted_fields()) {
        //print_r($ar_meta_fields);
        return 0;
    }
    //print_r($ar_meta_fields);
    
    // ----------------------- Create ------------------------
    if ($bean_id == "0") {
        switch ($module_name) {
			case "Calls":
			case "Meetings":
				$hdate_time = $ar_meta_fields['date_start']['value']." ".$ar_meta_fields['time_start']['value'];
				$ar_meta_fields['date_start']['value'] = time2db($hdate_time);
				break;
			default:
				break;
        }
        $bean_id = $sugar_soap_client->insert_record($ar_bean_descr);
        return $bean_id;
    } else {
        // ----------------------- Update ------------------------
        //print_r($ar_meta_fields);
        foreach($ar_meta_fields AS $key => $val) {
            if (isset($_POST[$key])) {
                
                switch ($ar_bean_descr['module_name']) {
					case 'Calls':
					case 'Meetings':
						if ($key == "date_start") {
							$date_komplett = $_POST['date_start_komplett'];
							$value = $ar_meta_fields[$key]['value'];
							$ar_meta_fields[$key]['value'] = $value." ".substr($date_komplett, 11);
						} else if ($key == "time_start") {
							$date_komplett = $_POST['date_start_komplett'];
							$value = $ar_meta_fields[$key]['value'];
							$key = 'date_start';
							$ar_meta_fields[$key]['value'] = substr($date_komplett, 0, 11).$value;
						}
						$ar_meta_fields['date_start']['value'] = time2db($ar_meta_fields['date_start']['value']);
						break;
					default:
						break;
                }
                
                if (!$sugar_soap_client->update_field($ar_meta_fields[$key], $bean_id)) {
                    return 0;
                }
            }
        }
    }
    return 1;
}


// ----------------------------------------------------------------
function sel_option_box($field) {
    $sel_ar = $field['options'];
    $fname = $field['fieldname'];
    $fval = $field['value'];
    
	$html = <<<__BLOCK__
	<select name="$fname" >
__BLOCK__;
	echo $html;
	
    foreach($sel_ar as $key => $name) {
        if ($fval == $key) {
			$html = <<<__BLOCK__
			<option value="$key" selected="selected">$name</option>
__BLOCK__;
			echo $html;
        } else {
			$html = <<<__BLOCK__
			<option value="$key"         >$name</option>
__BLOCK__;
			echo $html;
        }
    }
	$html = <<<__BLOCK__
	</select>
__BLOCK__;
	echo $html;
}


// ----------------------------------------------------------------
function single_edit_field($field, $tr_odd, $with_submit=1) {
    $hlabel = $field['label'];
    
	$html = <<<__BLOCK__
	<tr $tr_odd><td colspan="2">
__BLOCK__;
	echo $html;
	
    switch ($field['fieldtype']) {
		case 'hidden':
			break;	
		case 'show_only':
			$html = <<<__BLOCK__
			$hlabel<br />
__BLOCK__;
			echo $html;
			break;	
		case 'search_enum':
			$html = <<<__BLOCK__
			$hlabel<br />
			<input type="submit"  name="btn_search" value="search" tabindex="99" />
__BLOCK__;
			echo $html;
			break;	
		default:
			$html = <<<__BLOCK__
			$hlabel<br />
__BLOCK__;
			echo $html;
			if ($with_submit) {
				$html = <<<__BLOCK__
				<input type="submit"  name="btn_update" value="ok" tabindex="99" />
__BLOCK__;
			echo $html;
			}
			break;
    }
    
    get_edit_field($field);
    
	$html = <<<__BLOCK__
	</td></tr>
__BLOCK__;
	echo $html;

}

// ----------------------------------------------------------------
function get_edit_field($field) {
    global $ar_meta_fields, $sugar_soap_client;
    
    $fname = $field['fieldname'];
    $flabel = $field['label'];
    $fval = $field['value'];
    $err_str = $field['err_str'];
    //if ($fname =="name")
    //  print_r($field);
    if ($fname == "assigned_user_id") {
        $ar_users = $sugar_soap_client->get_users();
        $options = array();
        $har = array();
        for ($i=1; $i < count($ar_users); $i++) {
            $val = $ar_users[$i]['val'];
            $name = $ar_users[$i]['text'];
            
            $har[$name.$i]['id'] = $val;
            $har[$name.$i]['name'] = $name;
        }
        
        ksort($har);
        foreach($har as $key => $val) {
            $id = $val['id'];
            $name = $val['name'];
            $options[$id] = $name;
        }
        $field['options'] = $options;
        if (!isset($field['value'])) {
            $field['value'] = $GLOBALS['_SESSION']['authenticated_user_id'];
        }
    }
    
    switch ($field['fieldtype']) {
		case 'show_only':
			echo $fval;
			break;
		case 'text':
		case 'textarea':
			$html = <<<__BLOCK__
			<textarea  name="$fname" rows="8" cols="40">".$fval."</textarea>
__BLOCK__;
			echo $html;
			break;
		case 'duration':
			$hours = $ar_meta_fields['duration_hours']['value'];
			$html = <<<__BLOCK__
			<input type="text" name="duration_hours" value="$hours" class="width-verysmall" /> : 
__BLOCK__;
			echo $html;
			sel_option_box($ar_meta_fields['duration_minutes']);
			break;
		case 'enum':
			sel_option_box($field);
			break;
		case 'hidden':
			$html = <<<__BLOCK__
			<input type="hidden" name="$fname" value="$fval" />
__BLOCK__;
			echo $html;
			break;
		case 'search_enum':
			$html = <<<__BLOCK__
			<input type="text" name="$fname" value="$fval" class="width-standard" tabindex="98" />
__BLOCK__;
			echo $html;
			break;
		default:
			$html = <<<__BLOCK__
			<input type="text" name="$fname" value="$fval" class="width-standard" tabindex="98" />
__BLOCK__;
			echo $html;
			break;
    }
    
    if ($err_str != "") {
		$html = <<<__BLOCK__
		<br /><font color="red">$err_str</font>

__BLOCK__;
		echo $html;
    }
}

// ----------------------------------------------------------------
function create_record($ar_bean_descr) {
    global $ar_meta_fields, $account_id, $account_name, $sugar_soap_client;
    
    $now_date = date("Y-m-d");
    $now_time = date("H:i");
    
    $tr = 1;
    if (!isset($ar_meta_fields)) {
        // $sugar_soap_client->getMetaData($ar_bean_descr);
    }
    
    foreach($ar_meta_fields as $key => $val) {
        if (!$val['required']) {
            continue;
        }
        
        if ($tr%2) {
            $tr_odd = 'class="tr-odd"';
        } else {
            $tr_odd = 'class="tr-even"';
        }
        
        single_edit_field($ar_meta_fields[$key], $tr_odd, 0);
        if ($ar_meta_fields[$key]['fieldtype'] != "hidden") {
            $tr++;
        }
    }
    
	$html = <<<__BLOCK__
	<tr><td colspan="2"><input type="submit"  name="btn_create" value="ok" /></td></tr>
__BLOCK__;
	echo $html;
	
}

// ----------------------------------------------------------------
function detail_view($bean, $bean_id) {
    global $ar_beans, $ar_meta_fields, $sugar_soap_client;
    
    $hidden_fields = "";
    switch ($bean) {
		case "Call":
		case "Meeting":
			$ar_meta_fields['date_start']['value'] = db2time($ar_meta_fields['date_start']['value']);
			$hidden_fields.= '<input type="hidden" name="date_start_komplett" value ="' . $ar_meta_fields['date_start']['value'] .'" />';
			$ar_meta_fields['time_start']['value'] = substr($ar_meta_fields['date_start']['value'], 11, 5);
			$ar_meta_fields['date_start']['value'] = substr($ar_meta_fields['date_start']['value'], 0, 10);
			break;
		default:
			break;
    }
    
    $tr = 1;
    $par_str = "iphone.php?".get_location_par();
    foreach($ar_meta_fields as $key => $field) {
        $field = $ar_meta_fields[$key];
        if (!$field['visible']) {
            continue;
        }
        
        if ($tr%2) {
            $tr_odd = 'class="tr-odd"';
        } else {
            $tr_odd = 'class="tr-even"';
        }
        
        $hlabel = $field['label'];
        
        $hval =  $field['value'];
        
        $edit_field = "";
        if (isset($GLOBALS['_GET']['field'])) {
            $edit_field = $GLOBALS['_GET']['field'];
        }
        
        if (($edit_field == $key)||(isset($field['err_str']) && ($field['err_str'] != ""))) {
            single_edit_field($field, $tr_odd);
        } else {
            if ($key == 'parent_id') {
                if (isset($ar_meta_fields['parent_id'])) {
                    //die(print_r($ar_meta_fields['parent_id'], true));
                    if (!empty($ar_meta_fields['parent_id']['value'])) {
                        $id = $ar_meta_fields['parent_id']['value'];
                        $hmodule = $ar_meta_fields['parent_type']['value'];
                        $hval = $sugar_soap_client->getParentName($id, $hmodule);
                        $hmodule = $ar_meta_fields['parent_type']['value'];
                        $href = "iphone.php?modus=detail&bean=$hmodule&bean_id=$id";
						
						$html = <<<__BLOCK__
						<tr $tr_odd>
						<td>Related to</td>
						<td>$hmodule<br />
						<a href="$href">$hval</a>
						</td>
						</tr>
__BLOCK__;
						echo $html;
						
                    } else {
                        $tr--;
                    }
                }
            } else {
                $ftype = $field['fieldtype'];
                $href = $par_str."&amp;field=$key";
                
                switch ($ftype) {
					case "hidden":
						$tr--;
						continue;
						
					case "spacer":
						$html = <<<__BLOCK__
						<tr $tr_odd><td colspan="2">--- $hlabel ---</td></tr>
__BLOCK__;
						echo $html;
						break;
						
					case "duration":
						$hval = $ar_meta_fields['duration_hours']['value']  . ': ' . $ar_meta_fields['duration_minutes']['value'];
						$href.= "&amp;value=$hval";
						$html = <<<__BLOCK__
						<tr $tr_odd><td><a href="$href">$hlabel</a></td><td>$hval</td></tr>
__BLOCK__;
						echo $html;
						break;
						
					case "enum":
						$hval = $field['options'][$hval];
						$href.= "&amp;value=$hval";
						$format_value = nl2br($hval);
						$html = <<<__BLOCK__
						<tr $tr_odd><td><a href="$href">$hlabel</a></td><td>$format_value</td></tr>
__BLOCK__;
						echo $html;
						break;
						
					case "search_enum":
						$html = <<<__BLOCK__
						<tr $tr_odd><td>$hlabel</td><td>
__BLOCK__;
						echo $html;
						$mod1 = $ar_beans[$bean]['module_name'];
						$related_bean = $field['related_bean'];
						$mod2 = $ar_beans[$related_bean]['module_name'];
						$har = $sugar_soap_client->get_related($mod1, $bean_id, $mod2);
						//get_related($mod1, $bean_id, $mod2);";
						foreach($har as $hkey => $hval) {
							echo $hval['name']. '<br />';
						}
						
						$html = <<<__BLOCK__
						</td></tr>
						<tr $tr_odd><td>Add $hlabel</td><td>
__BLOCK__;
						echo $html;
						$scroll = get_par('scroll');
						
						if (isset($GLOBALS['_POST']['btn_list_ok']) || ($scroll != "")) {
							$list_bean = $field['related_bean'];
							// !!! important for search_enum
							$data_list_par = "bean=$bean&amp;modus=detail&amp;bean_id=$bean_id&amp;related_bean=$related_bean&amp;action=select";
							$par_name = 'sel_par';

							$html = <<<__BLOCK__
							<table>
__BLOCK__;
							echo $html;
							
							include("sugar-iphone-client/show_list.php");
							
							$html = <<<__BLOCK__
							</table>
__BLOCK__;
							echo $html;
							
						} else {
							$html = <<<__BLOCK__
							<input type="hidden" name="only_my_items" value="on" />
							<input type="submit"  name="btn_list_ok" value="search" tabindex="99" />
							<input type="text" name="search" value="$search" />
__BLOCK__;
							echo $html;

						}
						
						$html = <<<__BLOCK__
						</td></tr>
__BLOCK__;
						echo $html;
						
						break;
					case "show_only":
						$format_value = nl2br($hval);
						$html = <<<__BLOCK__
						<tr $tr_odd><td>$hlabel</td><td>$format_value</td></tr>
__BLOCK__;
						echo $html;
						break;
					case "phone":
						$phone_ref = getPhoneRef($hval);
						$href.= "&amp;field=$key&amp;value=$hval";
						$html = <<<__BLOCK__
						<tr $tr_odd><td><a href="$href">$hlabel</a></td><td>$phone_ref</td></tr>
__BLOCK__;
						echo $html;
						break;
					default:
						$href.= "&amp;field=$key&amp;value=$hval";
						$format_value = nl2br($hval);				
						$html = <<<__BLOCK__
						<tr $tr_odd><td><a href="$href">$hlabel</a></td><td>$format_value</td></tr>
__BLOCK__;
						echo $html;
						break;
                }
            }
        }
        $tr++;
    }
	$html = <<<__BLOCK__
	<tr $tr_even><td colspan="2">$hidden_fields</td></tr>
__BLOCK__;
	echo $html;
	
}

function getPhoneRef($phone) {
    global $config;
    $har = str_split($phone);
    $clean_phone="";
    
    foreach($har as $key => $val) {
        if((($val >= '0') && ($val <= '9')) || ($val == '+'))
        $clean_phone.=$val;
    }
    
    $result_ref = '<a href="' . $config['phone_ref'] . $clean_phone. '" target="dial">' . $phone . '</a>';
    return $result_ref;
}
?>

